#!/usr/bin/python
# -*- coding: utf-8 -*-

from PyQt5.QtCore import QEvent, QTimer, QByteArray, QBuffer, QIODevice
from PyQt5.QtGui import QGuiApplication, 

# example: https://code.qt.io/cgit/qt/qtserialport.git/tree/?h=5.14

class Clipboard(object):
    def __init__(self):
        super(Clipboard, self).__init__()
        self.app = QGuiApplication([])
        self.clipboard = self.app.clipboard()

    def getText(self, text):
        return self.clipboard.text()
    
    def setText(self, text):
        self.clipboard.setText(text)
        # each 20000 char wait 50ms
        wait_time = len(text) / 100000 * 5
        print "wait_time: %d, len: %d"%(wait_time, len(text))
        # if len(text) 
        QTimer.singleShot(wait_time, self.app.quit)
        self.app.exec_()
    
    def jpg2base64htmlimg(self, quality=100):
        mimedata = self.clipboard.mimeData()
        # if mimedata.hasImage():
        #     mimedata.imageData()
        if mimedata.hasImage():
            image = self.clipboard.image()
            # print image, image.size()
            ba = QByteArray()
            buffer = QBuffer(ba)
            buffer.open(QIODevice.WriteOnly)
            image.save(buffer, "jpeg", quality=quality)
            # res = image.save(buffer, "png")
            buffer.close()
            return '<image src="data:image/jpeg;base64,%s" alt="clip-image" />'%(ba.toBase64())
            # print str(a).encode("utf-8")
        else:
            print "no image in clipboard"

def main():
    jpg_html = Clipboard().jpg2base64htmlimg(quality=10)
    if jpg_html != None:
        Clipboard().setText(jpg_html)

    
if __name__ == "__main__":
    main()
